package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.util.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.jwtUtil.JwtUtils;
import com.qk.domain.user.UserDo;
import com.qk.dto.user.LoginDto;
import com.qk.dto.user.UserDto;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@SuppressWarnings("all")
public class UserServiceImpl  implements UserService {
    @Autowired
    private UserMapper userMapper;

    private static final String SALT = "123";
    private static final Integer USER_STATUS_NORMAL = 1;
    private static final Integer USER_STATUS_DISABLE = 0;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageResult<UserDo> getUser(UserDto userDto) {
        PageHelper.startPage(userDto.getPage(),userDto.getPageSize());
        List<UserDo> userList = userMapper.getUsers(userDto);
        Page<UserDo> rs =(Page<UserDo>) userList;
        return PageResult.<UserDo>builder()
                .total((int)rs.getTotal())
                .rows(userList)
                .build();
    }

    @Override
    public void addUser(User user) {
//        1、参数校验
        boolean b = BeanUtil.hasNullField(user, "id","deptId","password", "roleId", "image", "remark", "createTime", "updateTime");
        if(b){
//            throw new CommonException(ParamEnum.PARAM_ERROR);
//            CastExceptions.throwException(UserEnum.USER_ADD_PARM_ERROR);
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
//        设置密码、用户名+123
//        user.setPassword(DigestUtils.md5DigestAsHex((user.getUsername()+SALT).getBytes()));
        String password = new StringBuilder(user.getUsername()).append(SALT).toString();
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
    }

    @Override
    public void deleteUser(List<Integer> ids) {
        boolean isNotEmpty = CollectionUtil.isNotEmpty(ids);
        if(!isNotEmpty){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        userMapper.deleteUser(ids);
    }

    @Override
    public User selectById(Integer userid) {
        return  userMapper.selectById(userid);
    }

    @Override
    public List<User> selectList() {
       return userMapper.selectList();
    }

    @Override
    public List<User> selectByRole(String roleLabel) {
        return userMapper.selectByRole(roleLabel);
    }

    @Override
    public List<User> selectByDept(Integer deptId) {
        return userMapper.selectByDept(deptId);
    }

    @Override
    public void updateUser(User user) {
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateUser(user);
    }

    @Override
    public LoginVO login(LoginDto loginDto) {
        //1、参数校验
        boolean b = BeanUtil.hasNullField(loginDto);
        if(b){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        //2、根据用户名查询用户
        User user = userMapper.selectByuserName(loginDto.getUsername());
        //合法性校验
        if(Objects.isNull(user)){
            CommonException.throwCommonException(ParamEnum.LOGIN_USERNAME_ERROR);
        }
        if(ObjectUtil.equals(USER_STATUS_DISABLE,user.getStatus())){
            CommonException.throwCommonException(ParamEnum.LOGIN_USER_DISABLE);
        }
        //3、密码校验
//        String s = loginDto.getPassword();
        String s = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        String u = user.getPassword();
        boolean isChecked=Objects.equals(s,u);
        if(!isChecked){
            CommonException.throwCommonException(ParamEnum.LOGIN_PASSWORD_ERROR);
        }
        Map<String,Object> claims = new HashMap<>();
        claims.put("username",loginDto.getUsername());
        claims.put("id",user.getId());
        //4、返回用户信息
        Role role = roleMapper.selectById(user.getRoleId());
        return LoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .name(user.getName())
                .image(user.getImage())
                .roleLabel(role.getLabel())
                .token(JwtUtils.generateToken( claims))
                .build();
    }
}
